package com.common.groovy.helper;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import groovy.lang.Binding;
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyShell;
import groovy.lang.Script;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.Map;

/**
 * @Description:
 * @Date: 2025/6/30 14:19
 */
@Component
public class GroovyHelper {

    @Autowired
    private Binding binding;

    private final Logger logger = LoggerFactory.getLogger(GroovyHelper.class);

    public Object execute(String shell, JSONObject params) {
        GroovyClassLoader groovyClassLoader = new GroovyClassLoader();
        if (!ObjectUtils.isEmpty(params)){
            binding.setVariable("params", params);
        }
        binding.setVariable("log", logger);
        binding.setVariable("currentUserId", SecurityContextHolder.getContext().getAuthentication().getPrincipal());
        GroovyShell groovyShell = new GroovyShell(groovyClassLoader, binding);
        shell = fillScript(shell);
        Script script = groovyShell.parse(shell);
        return script.run();
    }

    private String fillScript(String shell) {
        StringBuffer fillScript = new StringBuffer();
        fillScript.append("import cn.hutool.json.*;\n");
        fillScript.append(shell);
        return fillScript.toString();
    }
}
